package alarm.ruiqi.com.alarm_pro.options.weather_forcast;


import android.app.Activity;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

import com.ab.fragment.AbAlertDialogFragment;
import com.ab.util.AbDateUtil;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbWifiUtil;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.google.gson.Gson;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SynthesizerListener;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.LogUtils;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.view.ViewHelper;

import java.util.Date;
import java.util.Random;

import alarm.ruiqi.com.alarm_pro.R;
import alarm.ruiqi.com.alarm_pro.domain.WeatherInfo;
import alarm.ruiqi.com.alarm_pro.options.MainActivity;
import alarm.ruiqi.com.alarm_pro.service.LocationService;
import alarm.ruiqi.com.alarm_pro.service.MobileApplication;
import alarm.ruiqi.com.alarm_pro.service.SpeechServiceImpl;
import alarm.ruiqi.com.alarm_pro.utils.Constant;
import alarm.ruiqi.com.alarm_pro.utils.RequestURL;

import static alarm.ruiqi.com.alarm_pro.utils.Constant.NET;
import static alarm.ruiqi.com.alarm_pro.utils.Constant.NoNET;
import static alarm.ruiqi.com.alarm_pro.utils.Constant.WIFI;

public class WeatherForcastFragment extends Fragment implements MainActivity.MainActivityInterInteractionListener {




    private TextInputLayout mTxtLayout;
    private FloatingActionButton mPlayButton,mStopButton;
    private TextView mMsg;
    private ScrollView scroll;
    private SpeechServiceImpl mSpeechService;

    public static final int MSG_MTS = 0x0001; //语音合成
    public static final int MSG_WEATHER_RESOLVE= 0x0002; //解析数据
    public static final int MSG_LOCATION = 0x0003; //语音合成

    // 缓冲进度
    private int mPercentForBuffering = 0;
    // 播放进度
    private int mPercentForPlaying = 0;

    private CharSequence weatherInfo;
    private LocationService mService;

    public WeatherForcastFragment() {

    }

    //region 生命周期
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity)activity).getmDrawerLayout().setBackgroundResource(R.mipmap.weather_bg);
        ((MainActivity)activity).getHeadFragment().addRightDrawable(R.drawable.abc_ic_clear_mtrl_alpha, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMsg.setText("");
            }
        });
        ((MainActivity)activity).setMainActivityInterInteractionListener(this);
        mSpeechService = SpeechServiceImpl.getInstance();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mService  = MobileApplication.getInstance().getLocatioService();
        mService.stopLocation();
        //检查网络状态
        if (AbWifiUtil.isWifiConnectivity(getActivity())){
            //wifi
          //  AbDialogUtil.showAlertDialog(getActivity(), "注意", "当前为wifi", new MyDialogListener(Constant.WIFI));
        }else if (AbWifiUtil.isConnectivity(getActivity())){
            //2g
            AbDialogUtil.showAlertDialog(getActivity(),"注意","当前为数据连接,可能会收取额外的费用,确定要继续吗?",new MyDialogListener(Constant.NET));
        }else {
            AbDialogUtil.showAlertDialog(getActivity(), "注意", "当前没有网络,确定要继续吗?",new MyDialogListener(Constant.NoNET));
        }

    }

    @Override
    public void onDetach() {
        super.onDetach();
        ((MainActivity)getActivity()).getmDrawerLayout().setBackgroundResource(R.color.transparent);
        ((MainActivity)getActivity()).addMenu();
    }

    @Override
    public void onStop() {
        super.onStop();
        mSpeechService.stopSpeeking();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View parentView =  inflater.inflate(R.layout.fragment_weather_forcast, container, false);
        mPlayButton = (FloatingActionButton) parentView.findViewById(R.id.weather_forcast_play);
        mTxtLayout = (TextInputLayout) parentView.findViewById(R.id.weather_forcast_txt_input);
        EditText editText = mTxtLayout.getEditText();
        editText.setText("");
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 8) {
                    if (mPlayButton.isEnabled()) {
                        mTxtLayout.setErrorEnabled(true);
                        mTxtLayout.setError("长度超出范围");
                        togglePalyButton(false);
                    }
                } else if (s.length() < 2) {
                    if (mPlayButton.isEnabled()) {
                        mTxtLayout.setErrorEnabled(true);
                        mTxtLayout.setError("长度不足");
                        togglePalyButton(false);
                    }
                } else {
                    if (!mPlayButton.isEnabled()) {
                        mTxtLayout.setErrorEnabled(false);
                        togglePalyButton(true);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        mPlayButton.setTag(0);
        mPlayButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch ((int) mPlayButton.getTag()) {
                    case R.mipmap.videoplayer_icon_play_highlighted:
                        mSpeechService.resumeSpeeking();
                        changeButtonState(false);
                        break;
                    case R.mipmap.videoplayer_icon_stop_highlighted:
                        mSpeechService.pauseSpeeking();
                        changeButtonState(true);
                        break;
                    default:
                        final String city = mTxtLayout.getEditText().getText().toString();
                        appendMsg("请求地址确认：" + city);
                        HttpUtils httpUtils = new HttpUtils(5000);
                        httpUtils.send(HttpRequest.HttpMethod.GET, RequestURL.getWeatherForcast(city,
                                new Random().nextInt(2)), weathercallBack);
                        break;

                }


            }
        });
        mStopButton =(FloatingActionButton) (parentView).findViewById(R.id.weather_forcast_stop);
        mStopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtils.i("mStopButton onClick");
                mSpeechService.stopSpeeking();
                replcaeCurrentMsg(mMsg.getText(),true);
                appendMsg("停止播放");
                toggleStopButton(false);
                changeButtonState(true);
                mPlayButton.setTag(0);
            }
        });
        mMsg = (TextView) parentView.findViewById(R.id.weather_forcast_txt_msg);
        scroll = (ScrollView) parentView.findViewById(R.id.weather_forcast_scroll);

        //开始设置定位
        appendMsg("开始获取定位信息...");
        initialLocation();
        return parentView;
    }

    private void togglePalyButton(boolean enabled) {
        mPlayButton.setEnabled(enabled);
        mPlayButton.setBackgroundTintList(enabled ? ColorStateList.valueOf(getResources().getColor(R.color.tomato)) : ColorStateList.valueOf(getResources().getColor(R.color.antique_white_disable)));
    }

    private  void changeButtonState(boolean isPlay){
        if (mPlayButton.isEnabled()){
            mPlayButton.setImageResource(isPlay?R.mipmap.videoplayer_icon_play_highlighted:R.mipmap.videoplayer_icon_stop_highlighted);
            mPlayButton.setTag(isPlay?R.mipmap.videoplayer_icon_play_highlighted:R.mipmap.videoplayer_icon_stop_highlighted);
        }
    }

    //endregion

    //region 与MainActivity 交互接口的实现
    //*********************** ************************************//
    //                   MainActivity 交互                         //
    //***********************  ************************************//
    @Override
    public void onDrawerSlide(float slideOffset) {
        ViewHelper.setTranslationX(mPlayButton, slideOffset / 2);
    }
    //endregion



    //region Msg文本处理
    private void appendMsg(CharSequence msg){
        mMsg.setText(TextUtils.concat(mMsg.getText(),
                Html.fromHtml(TextUtils.concat("<font color='#FF6347'>", AbDateUtil.getStringByFormat(new Date(), AbDateUtil.dateFormatYMDHMS), "</font>").toString()),
                " : ", msg, System.getProperty("line.separator")));
        scroll.post(new Runnable() {
            @Override
            public void run() {
                scroll.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }

    private void replcaeCurrentMsg(CharSequence preMsg ,boolean isNewLine,CharSequence ...msg) {
        mMsg.setText(TextUtils.concat(new CharSequence[]{preMsg, TextUtils.concat(msg), isNewLine ? System.getProperty("line.separator") : ""}));
        scroll.post(new Runnable() {
            @Override
            public void run() {
                scroll.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }
    //endregion

    //网络请求回掉函数
    private  RequestCallBack<String> weathercallBack = new RequestCallBack<String>() {

        private CharSequence currentMsg ;
        private  long mCurrent;
        @Override
        public void onStart() {
            super.onStart();
            appendMsg("开始请求天气数据,请稍后...");
            togglePalyButton(false);
            mCurrent = 0;
            replcaeCurrentMsg(mMsg.getText(),false, Html.fromHtml(TextUtils.concat("<font color='#FF6347'>", AbDateUtil.getStringByFormat(new Date(), AbDateUtil.dateFormatYMDHMS), "</font>", " : ").toString()));
            currentMsg =mMsg.getText();
            replcaeCurrentMsg(currentMsg,false,TextUtils.concat("当前进度","0%"));

        }

        @Override
        public void onSuccess(ResponseInfo<String> responseInfo) {

          //  LogUtils.i(responseInfo.result);
            if (responseInfo.contentLength<=0){
                replcaeCurrentMsg(currentMsg,true,TextUtils.concat("当前进度","100%"));
            }

            Message msg = Message.obtain();
            msg.what = MSG_WEATHER_RESOLVE;
            msg.obj = responseInfo.result;
            mTsHandler.sendMessage(msg);


        }

        @Override
        public void onFailure(HttpException e, String s) {
            replcaeCurrentMsg(currentMsg,true,TextUtils.concat("当前进度","0%"));
            appendMsg("请求天气数据失败...请重试");
            togglePalyButton(true);
        }

        @Override
        public void onLoading(long total, long current, boolean isUploading) {
            super.onLoading(total, current, isUploading);
         //   replcaeCurrentMsg(currentMsg,current/total*100+"%",current==total);

            if (total<=0){
                if (current ==0) current =1;
                replcaeCurrentMsg(currentMsg,false,TextUtils.concat("当前进度",mCurrent/current*100+"","%"));
            }else {
                replcaeCurrentMsg(currentMsg,current==total,current/total*100+"%");
            }
            mCurrent =current;
        }
    };

    class MyDialogListener implements AbAlertDialogFragment.AbDialogOnClickListener {
       private String mTag;

       public  MyDialogListener(String tag){
           mTag = tag;
       }

        @Override
        public void onPositiveClick() {
            switch (mTag){
                case WIFI:
                    break;
                case NET:
                    break;
                case NoNET:
                    break;
            }
        }

        @Override
        public void onNegativeClick() {

        }
    };


    //回调handler
    private Handler mTsHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            WeatherInfo info;
            switch (msg.what){
                case  MSG_MTS:
                    appendMsg("开始语音合成...");
                    info  = (WeatherInfo) msg.obj;
                    weatherInfo = info.getWeatherInfo();
                    int code =   mSpeechService.startSpeaking(weatherInfo.toString(),mTtsListener);
                    if (code != ErrorCode.SUCCESS) {
                        if(code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED){
                            //未安装则跳转到提示安装页面
                            appendMsg("ERROR_COMPONENT_NOT_INSTALLED");
                            togglePalyButton(true);
                        }else {
                            appendMsg("语音合成失败,错误码: " + code);
                        }
                    }
                    break;

                case  MSG_WEATHER_RESOLVE:

                    appendMsg("请求天气数据成功，开始解析数据...");
                    Gson gson = new Gson();
                     info = gson.fromJson(msg.obj.toString(),WeatherInfo.class);
                    if (info.getError()!=0){
                        //错误
                        appendMsg("天气数据错误:"+info.getStatus()+",请检查输入的城市或地区名称...");
                        togglePalyButton(true);
                        return;
                    }else {
                        appendMsg("天气数据解析成功...");
                    }
                    msg =Message.obtain();
                    msg.what = MSG_MTS;
                    msg.obj = info;
                    mTsHandler.sendMessage(msg);

                    break;

                case MSG_LOCATION:

                    if (TextUtils.isEmpty(LocationService.Location_City) &&TextUtils.isEmpty(LocationService.Location_District)){
                        //appendMsg("重新定位中...,当前请求次数"+Constant.RETRY_TIMES);

                        //重新请求
                        mService.setLocationListener(new BDLocationListener() {

                            private  int i = 0;
                            @Override
                            public void onReceiveLocation(BDLocation bdLocation) {
                                LogUtils.i("onReceiveLocation"+this);
                                i+=1;
                                appendMsg("重新定位中...,当前请求次数"+(i));

                                if (LocationService.isLocationOK(bdLocation.getLocType())) {
                                    LocationService.Location_City = bdLocation.getCity();
                                    LocationService.Location_District = bdLocation.getDistrict();
                                    if (!TextUtils.isEmpty(LocationService.Location_City)){
                                        mTxtLayout.getEditText().setText(LocationService.Location_City);
                                    }
                                    if (!TextUtils.isEmpty(LocationService.Location_District)){
                                        mTxtLayout.getEditText().setText(LocationService.Location_District);
                                    }
                                    appendMsg("定位成功！");
                                    mService.stopLocation();
                                } else {
                                    LocationService.Location_City = "";
                                    LocationService.Location_District = "";
                                    if (i> Constant.RETRY_TIMES_MAX) {
                                        i=0;
                                        mService.stopLocation();
                                        mTsHandler.sendEmptyMessage(0x99);

                                    }
                                }

                            }
                        });
                        mService.startLocation();
                        return;
                    }
                    if (!TextUtils.isEmpty(LocationService.Location_City)){
                        mTxtLayout.getEditText().setText(LocationService.Location_City);
                    }
                    if (!TextUtils.isEmpty(LocationService.Location_District)){
                        mTxtLayout.getEditText().setText(LocationService.Location_District);
                    }
                    appendMsg("定位成功！");


                    break;

                case 0x99:
                    appendMsg("定位失败，请检查网络或者打开GPS，您也可以手动输入地址...");
                    break;
            }
        }
    };

    /**
     * 合成回调监听。
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {


        private  CharSequence AllPre, pre ;
        private Snackbar snackbar ;
        private  int endpos = -1;

        private  void showSnacktext(CharSequence sequence){
            snackbar.setText(sequence);
            snackbar.show();
        }

        public void onSpeakBegin() {
            togglePalyButton(true);
            changeButtonState(false); //暂停
            toggleStopButton(true);
            appendMsg("语音合成成功,开始播放...");
            snackbar =Snackbar.make(getView(), "", Snackbar.LENGTH_LONG);
            showSnacktext(String.format(getString(R.string.tts_toast_format),
                    mPercentForBuffering, mPercentForPlaying));
            AllPre = mMsg.getText();
            pre = Html.fromHtml(TextUtils.concat("<font color='#FF6347'>", AbDateUtil.getStringByFormat(new Date(), AbDateUtil.dateFormatYMDHMS), "</font>", " : ").toString());

            // showTip("开始播放");
        }

        @Override
        public void onSpeakPaused() {
//           showTip("暂停播放");
            showSnacktext("暂停播放");
        }

        @Override
        public void onSpeakResumed() {
//            showTip("继续播放");
            showSnacktext("继续播放");
        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos,
                                     String info) {
            // 合成进度
            mPercentForBuffering = percent;
            showSnacktext(String.format(getString(R.string.tts_toast_format),
                    mPercentForBuffering, mPercentForPlaying));

            LogUtils.i("beginPos =" + beginPos + "; endPos = " + endPos + ";info=  " + info);
            this.endpos = endPos;
        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
            // 播放进度
            mPercentForPlaying = percent;
            showSnacktext(String.format(getString(R.string.tts_toast_format),
                    mPercentForBuffering, mPercentForPlaying));
            LogUtils.i("beginPos =" + beginPos + "; endPos = " + endPos + ";");
            if (this.endpos != endPos ){
                CharSequence charSequence =  weatherInfo.subSequence(0, endPos);
                AllPre =TextUtils.isEmpty(mMsg.getText())?"":AllPre;
                replcaeCurrentMsg(AllPre,endPos == weatherInfo.length() -1,pre,charSequence);
            }


        }

        @Override
        public void onCompleted(SpeechError error) {
            toggleStopButton(false);
            togglePalyButton(true);
            mPlayButton.setTag(0); //开始
            replcaeCurrentMsg(mMsg.getText(),true);
            if (error == null) {
                appendMsg("播放完成");
            } else if (error != null) {
                appendMsg("播放未成功："+error.getPlainDescription(true));
            }
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //		Log.d(TAG, "session id =" + sid);
            //	}
        }
    };

    private void toggleStopButton(final boolean flag){
         YoYo.with(flag? Techniques.RollIn : Techniques.RollOut).withListener(new AnimatorListenerAdapter() {
             @Override
             public void onAnimationEnd(Animator animation) {
                 super.onAnimationEnd(animation);
                 if (!flag){
                     mStopButton.setVisibility(View.GONE);
                 }
             }

             @Override
             public void onAnimationStart(Animator animation) {
                 super.onAnimationStart(animation);
                 if (flag){
                     mStopButton.setVisibility(View.VISIBLE);
                 }
             }
         }).interpolate(new AccelerateInterpolator()).duration(500).playOn(mStopButton);

    }


    private void initialLocation() {
        Message msg = Message.obtain();
        msg.what =MSG_LOCATION;
        mTsHandler.sendMessage(msg);
    }


}
